import { Body, Controller, Get, Param, Post, Query } from "@nestjs/common";
import { AccountService } from "./account.service";
import { Account } from "./account.entities";
import { QuantityExceededException } from "../../exception/count.limit.exception";

@Controller("account")
export class AccountController {
  constructor(private readonly accountService: AccountService) {}

  /**
   * 获取账号表
   * @param params
   * @returns
   */
  @Get("/account_list")
  async page() {
    try {
      const result = await this.accountService.getAccountList();
      return {
        data: {
          list: result.accounts,
          total: result.total,
        },
        code: 200,
        message: "获取成功",
      };
    } catch (err) {
      return Promise.reject(err);
    }
  }
  /**
   * 创建账号
   */
  @Post("/create")
  async create(@Body() account: Account) {
    account.created_time = new Date();
    account.modified_time = new Date();

    try {
      const newAccount = await this.accountService.createAccount(account);
      return {
        data: newAccount,
        code: 200,
        message: "创建成功",
      };
    } catch (err) {
      console.log("err: ", err);
      if (err instanceof QuantityExceededException) {
        throw err;
      } else {
        return Promise.reject(err);
      }
    }
  }
  /**
   * 删除账号
   */
  @Post("/delete")
  async delete(@Body() account: Account) {
    if (!account.id) {
      return {
        data: null,
        code: 400,
        message: "缺少id",
      };
    }

    try {
      await this.accountService.deleteAccount(account.id);
      console.log('id: ', account.id);
      return {
        data: null,
        code: 200,
        message: "删除成功",
      };
    } catch (err) {
      console.log("err: ", err);
      if (err instanceof QuantityExceededException) {
        throw err;
      } else {
        return Promise.reject(err);
      }
    }
  }
  /**
   * 更新账号
   */
  @Post("/update")
  async update(@Body() account: Account) {
    account.created_time = new Date();
    account.modified_time = new Date();

    if (!account.id) {
      return {
        data: null,
        code: 400,
        message: "缺少id",
      };
    }

    try {
      const newAccount = await this.accountService.updateAccount(account);
      return {
        data: newAccount,
        code: 200,
        message: "更新成功",
      };
    } catch (err) {
      console.log("err: ", err);
      if (err instanceof QuantityExceededException) {
        throw err;
      } else {
        return Promise.reject(err);
      }
    }
  }
}
